<?php

class BIS_Controller_Plugin_SessionCheck extends Zend_Controller_Plugin_Abstract
{
    /**
     * preDispatch
     */
    public function preDispatch (Zend_Controller_Request_Abstract $request)
    {
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $options = $bootstrap->getOption("excludeAuthPages");
        $requestObject = $this->getRequest();
        $controller = $requestObject->getControllerName();
       
        if (!in_array($controller, $options)) {

            $module = $requestObject->getModuleName();

            $module = ucfirst($module);
            //Instantiate the module specific authentication service
            $authService = $module."_Service_Authentication";
            $authService = new $authService();

            if (!$authService->getAuth()->hasIdentity()) {
                $relocate = $this->getRequest()->getBaseUrl().'?redir='.urlencode($this->getRequest()->getRequestUri());
                $this->getResponse()->setRedirect($relocate)->sendResponse();
                exit;
            }

            $controller = $requestObject->getControllerName();
            $action = $requestObject->getActionName();
            $do = $requestObject->getParam('do');

            $resource = $controller.'/'.$action;

            //get the module resource service
            $resourceService = $module."_Service_Resource";
            $resourceService = new $resourceService();
            $resources = $resourceService->getAccessPermissions();

            if(in_array($resource, $resources)){
                //Instantiate the module specific access control list
                $acl = $module."_Model_Acl_".$module;
                $acl = new $acl($authService->getIdentity()->role);

                if (!$acl->isAllowed($authService->getIdentity()->role, $resource, $do)) {
                        $relocate =  $this->getRequest()->getBaseUrl().'/permission';
                        $this->getResponse()->setRedirect($relocate)->sendResponse();
                        exit;
                  }
            }else{
                throw new BIS_Exception_404('The page requested is not found, please refer to your system administrator for problem resolution.');
            }
        }
    }
    
}